import {Component, OnInit, Renderer2, ViewChild} from '@angular/core';
import {MagicScienceInnovateService} from './magic-science-innovate.service';
import {Page} from '../common/model/page';
import {EChartOption} from 'echarts';
import {NzTreeComponent, NzTreeNodeOptions} from 'ng-zorro-antd/tree';
import {HomeService} from '../home/home.service';
import {AreaAnalysisCondition} from '../content/model/area-analysis-condition';
import _ from 'lodash';

export class ScienceCondition extends Page {
  id?: number;

  constructor() {
    super();
    this.pageSize = 20;
    this.pageNum = 1;
  }
}

@Component({
  selector: 'app-magic-science-innovate',
  templateUrl: './magic-science-innovate.component.html',
  styleUrls: ['./magic-science-innovate.component.less']
})
export class MagicScienceInnovateComponent implements OnInit {
  treeNodes: NzTreeNodeOptions[] = [];
  scienceCondition = new ScienceCondition();
  sciencePolicyList = [];
  sciencePolicyListSimple = [];
  wordFreamCounts = [];
  wordFreamId = '';
  isSpinning;
  selectedValue = null;
  isExpand = [];
  last_selectedValue = null;        // 用于记录上次的搜索内容, 下次搜索时要去掉。
  listOfOption: Array<{ value: string; text: string }> = [];
  areaAnalysis = new AreaAnalysisCondition();
  tabList = [
    {name: '政策矩阵', router: '/home', active: false},
    {name: '政策文件', router: '/magic-science-innovate', active: true},
    {name: '政策专题', router: '/policy-analysis-matrix', active: false},
    {name: '计量分析', router: '/policy-analysis-chart', active: false},
  ];
  curSearchStr = '{}';        // 当前的搜索条件

  chartOption: EChartOption = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const tar = params[0];
        return tar.name + ':' + tar.value + '<br />' + '占比' + ':' + Math.floor(tar.data.percentage * 10000) / 100 + '%';
      }
    },
    grid: {
      left: '1%',
      right: '1%',
      top: 0,
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      // x轴标签隐藏
      axisLabel: {
        show: false
      },
      // x轴刻度隐藏
      axisTick: {
        show: false
      },
      // x轴线隐藏
      axisLine: {
        show: false
      },
      // grid区域内的分割线隐藏
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'category',
      axisLabel: {
        fontSize: 16
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      }
    },
    series: [{
      type: 'bar',
      barWidth: 16,
      itemStyle: {
        color: '#13ace8'
      },
    }]
  };
  updateData: EChartOption[] = [];

  objectKeys = Object.keys;


  @ViewChild('wordFrameTree') wordFrameTree!: NzTreeComponent;

  constructor(private magicSService: MagicScienceInnovateService,
              private renderer: Renderer2,
              private homeService: HomeService) {
  }

  ngOnInit(): void {
    // this.getTreeData();
    this.getPolicySortRegion();
  }


  search(inputValue: string) {
    this.homeService.getPreKey(inputValue).subscribe(res => {
      const listOfOption: Array<{ value: string; text: string }> = [];
      if (res.result.length) {
        // 如果当前搜索的词, 非后台关键词。则把它放在第一个展示。
        if (inputValue !== '' && res.result.indexOf(inputValue) === -1) {
          listOfOption.push({
            value: inputValue,
            text: inputValue
          });
        }
        res.result.forEach(item => {
          listOfOption.push({
            value: item,
            text: item
          });
        });
      } else {
        listOfOption.push({
          value: inputValue,
          text: inputValue
        });
      }
      this.listOfOption = listOfOption;
    });
  }

  // 首次点击时, 出的默认推荐。nz-select默认有此功能, nz-autocomplete需要单独支持。
  clickInput() {
    if (!this.selectedValue && this.listOfOption.length === 0) {
      this.search('');
    }
  }

  // 顶部搜索按钮
  searchContent() {
    //console.log('[searchContent]', this.selectedValue, this.last_selectedValue )
    if (this.selectedValue != this.last_selectedValue) {
      this.last_selectedValue = this.selectedValue;
      this.getPolicySortRegion();
    }
  }

  searchContent_clear() {
    this.selectedValue = null;
    this.last_selectedValue = null;
    this.getPolicySortRegion();
  }

  getPolicySortRegion() {

    let obj = Object.assign({pageSize:5}, this.areaAnalysis);

    // 合并顶部的搜索条件。
    if (!obj['key']) {
        obj['key'] = [];
    }
    if (this.selectedValue && obj['key'].indexOf(this.selectedValue) === -1) {
        obj['key'].push(this.selectedValue);
    }


    this.curSearchStr = JSON.stringify(obj);

    //console.log('[getPolicySortRegion]', this.selectedValue, obj);
    this.magicSService.getPolicySortRegion(obj).subscribe(res => {
      this.sciencePolicyList = res.result;
      let i = 0;
      for (const key of Object.keys(this.sciencePolicyList)) {
        // 只显示5条
        this.sciencePolicyList[key].policys.listSimple = _.slice(this.sciencePolicyList[key].policys.list, 0, 5);
        if( this.sciencePolicyList[key].policys.listSimple.length > 0){
              // 要从多到少
            this.chartMerge(this.sciencePolicyList[key].countWithKey.reverse(), i);
        }else{  // 如果没有政策列表, 则不要显示关键词的图。
            this.chartMerge([], i);
        }
        i++;
      }
    });
  }

  chartMerge(list: any, i: number) {
    const obj = this.nameAndCount(list);
    this.updateData[i] = {
      yAxis: {
        data: obj.nameList,
      },
      series: [{
        data: list,
        type: 'bar',
        barWidth: 16,
        itemStyle: {
          color: '#13ace8'
        },
      }]
    };
  }

  nameAndCount(list: any) {
    const nameList = [];
    const countList = [];
    for (const listElement of list) {
      if (listElement && listElement['name']) {
        nameList.push(listElement.name);
        countList.push(listElement.count);
      }
    }
    return {nameList, countList};
  }

  queryPolicy(condition: AreaAnalysisCondition) {
    //console.log('[queryPolicy]', condition ); return;
    this.areaAnalysis = condition;
    this.getPolicySortRegion();
  }

  // // 页码改变时回调
  // pageChange(event: number) {
  //   this.scienceCondition.pageNum = event;
  //   this.getNewPolicyList();
  // }
}
